﻿using Microsoft.AspNetCore.Mvc.ApplicationModels;

namespace Framework.WebApi.UnifyResult
{
	/// <summary>
	/// 控制器应用模型转换器
	/// </summary>
	public class ApiControllerApplicationModelConvention : IApplicationModelConvention
	{
		/// <summary>
		/// 服务集合
		/// </summary>
		private readonly IServiceCollection _services;

		public ApiControllerApplicationModelConvention(IServiceCollection services)
		{
			_services = services;
		}

		public void Apply(ApplicationModel application)
		{
			var controllers = application.Controllers.Where(u => Penetrates.IsApiController(u.ControllerType));
			foreach (var controller in controllers)
			{
				var controllerType = controller.ControllerType;

				foreach (var action in controller.Actions)
				{
					ConfigureActionUnifyResultAttribute(action);    // 配置规范化结果类型
				}
			}
		}

		/// <summary>
		/// 配置规范化结果类型
		/// </summary>
		/// <param name="action"></param>
		private static void ConfigureActionUnifyResultAttribute(ActionModel action)
		{
			// 判断是否手动添加了标注或跳过规范化处理
			if (SucceededUnifyResultFilter.CheckSucceededNonUnify(action.ActionMethod)) return;

			// 获取真实类型
			var returnType = action.ActionMethod.GetRealReturnType();
			if (returnType == typeof(void)) return;

			// 添加规范化结果特性
			action.Filters.Add(new UnifyResultAttribute(returnType, StatusCodes.Status200OK, action.ActionMethod));
		}
	}
}
